<script>
  /* global _ctxPath */
  import {useBaseInfoStore, useBaseInfoWithOut} from '@/store/modules/base-info';
  import { validateAttachment } from '@/helper/relation-attachment';
  import globalMethods from '@/plugins/methods';
  import {fireEvent, getCollEventParams} from "@/handles/common/sdk";
  import globalData from "@/plugins/data";
  import {mapState} from "pinia";

  export default {
    name: 'RelationAttachment',
    props: {
      // 已上传的附件列表
      fileList: {
        type: Array,
        default: () => ([]),
      },
      isNewMode: { // 是否为新组件模式
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        flag: false,
      };
    },
    computed: {
      ...mapState(useBaseInfoStore, ['businessData']),
    },
    methods: {
      async handleOpenDialog() {
        // 先校验业务密级是否设置
        if (!useBaseInfoWithOut().checkSecret()) return;
        let hook = await fireEvent('relationAttachment', getCollEventParams(this.businessData, globalData));
        if (!hook) {
          return;
        }

        const url = '/seeyon/ctp/common/associateddoc/assdocFrame.do?isBind=1,3&referenceId=&applicationCategory=1&poi=Att&exAssModules=3,6&relateAttachment=true&Zxchat=1&isNewStyle=true';
        const dialog = globalMethods.dialog({
          title: this.$i18n('common.toolbar.insert.relateAttachment.label'),
          bodyStyle: 'padding: 0',
          width: 1000,
          height:  window.top.innerHeight * 0.8,
          centered: true,
          dialogStyle: { 'padding-bottom': 0 },
          url,
          afterClose: () => {
            this.flag = false;
          },
          onCancel() {
            dialog.close();
          },
          onConfirm: () => {
            if (this.flag) return;
            this.flag = true;

            // 获取iframe上下文
            const ctx = dialog.dialog().contentWindow;
            // 获取选择的附件列表
            const attachmentList = ctx.fileUploadAttachments.values().toArray().map(item => ({
              ...item
              // subReference: '', // 后端会用这个值做判断，这是一个无效值，故做特殊处理
            }));

            // 未选择任何附件，则直接关闭弹框
            if (!attachmentList.length) return dialog.close();

            console.log('关联附件的逻辑',attachmentList);
            // 关联附件重复校验
            const repeatedAttachmentList = validateAttachment(attachmentList, this.fileList);
            if (!repeatedAttachmentList.length) {
              // 通知设置列表数据
              this.$emit('selected', this.attachmentGenerator(attachmentList));
              dialog.close();
            } else {
              this.$confirm({
                content: (
                  <div>
                    { repeatedAttachmentList.map(item => <section>{ item }</section>) }
                    <section>{ this.$i18n('common.toolbar.insert.relateAttachment.sameTips') }</section>
                  </div>
                ),
                onOk: () => {
                  // 通知设置列表数据
                  this.$emit('selected', this.attachmentGenerator(attachmentList));
                  dialog.close();
                },
                onCancel: () => {
                  this.flag = false;
                },
              });
            }
          },
        });
      },
      //关联附件的文件会从服务器拷贝一份
      attachmentGenerator(attachmentList){
        if (!attachmentList){
          return [];
        }
        let newRelateAttRes = window.callBackendMethod("relateAttachmentManager", "getRelateTargetAtt", {
          atts:attachmentList
        })
        const {atts=[]} = newRelateAttRes || {atts: []};
        atts.forEach(att => att.from = 'relationAtta');
        return atts;
      },
    },
    render() {
      return (
        <div id="relation-attachment" onClick={this.handleOpenDialog}>
          { !this.isNewMode && <i class="syIcon xicon-relate-att color-primary"></i> }
          <span class={this.isNewMode ? 'color-primary' : ''}>{ this.$i18n('common.toolbar.insert.relateAttachment.label') }</span>
        </div>
      );
    },
  };
</script>

<style lang="scss" scoped>
  #relation-attachment {
    display: flex;
    align-items: center;
    color: #333;
    cursor: pointer;

    &:hover {
      color: $primary-color;
    }

    > .relation-attachment-icon {
      width: 16px;
      height: 16px;
      margin-right: 4px;
    }
  }
</style>
